package com.tang.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.module.system.mapper.DeptMapper;
import com.tang.module.system.entity.Dept;
import com.tang.module.system.service.DeptService;
import com.tang.module.system.vo.DeptVo;
import com.tang.module.system.wrapper.DeptWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.PortResolverImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门表(Dept)表服务实现类
 *
 * @author tang
 * @since 2022-01-14 16:14:56
 */
@Service("deptService")
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

    @Autowired
    private DeptMapper deptMapper;


    @Override
    public List<DeptVo> tree(Integer deptCategory) {
        Dept searchDept = new Dept();
        searchDept.setDeptCategory(deptCategory);
        List<Dept> deptList = deptMapper.selectList(new QueryWrapper<>(searchDept));
        List<DeptVo> deptVos = deptList.parallelStream().map(dept -> DeptWrapper.build().wrapper(dept)).collect(Collectors.toList());
        return createTree(0L,deptVos);
    }

    @Override
    public List<DeptVo> createTree(Long fatherId, List<DeptVo> dataList) {
        //该集合存储了子节点
        List<DeptVo> children = new ArrayList<>();
        for (DeptVo dept : dataList) {
            //是否为当前节点的子节点
            if (dept.getParentId().equals(fatherId)){
                children.add(dept);
                //继续递归，寻找当前节点的字节点
                dept.setChildren(createTree(dept.getId(),dataList));
            }
        }
        return children;
    }
}
